package com.chinawlx.wlxteacher.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.chinawlx.wheelview.OptionsPickerView;
import com.chinawlx.wlxteacher.R;
import com.chinawlx.wlxteacher.network.WLXHttpRxHelper;
import com.chinawlx.wlxteacher.network.bean.WLXGetCodeBean;
import com.chinawlx.wlxteacher.utils.WLXConstant;
import com.chinawlx.wlxteacher.utils.WLXDateUtil;
import com.chinawlx.wlxteacher.utils.WLXGreenDaoUtil;
import com.chinawlx.wlxteacher.utils.WLXWheelViewUtils;
import com.chinawlx.wlxteacher.widget.WLXChooseLessonView;
import com.chinawlx.wlxteacher.widget.WLXCustomToast;
import com.chinawlx.wlxteacher.widget.radiogroup.WLXFlowRadioGroup;
import com.chinawlx.wlxteacher.wlx_schedule;
import com.chinawlx.wlxteacher.wlx_scheduleDao;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscriber;

import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;

/**
 * Created by wlx on 16/8/20.
 * 班级停课
 */
public class WLXClazzSuspendActivity extends WLXBaseActivity {
    @BindView(R.id.iv_back_clazz_suspend)
    ImageView mIvBackClazzSuspend;
    @BindView(R.id.tv_clazz_suspend)
    TextView mTvClazzSuspend;
    @BindView(R.id.tv_student_name_clazz_suspend)
    TextView mTvStudentNameClazzSuspend;
    @BindView(R.id.iv_adjust_clazz_suspend)
    ImageView mIvAdjustClazzSuspend;
    @BindView(R.id.leave_count)
    TextView mLeaveCount;
    @BindView(R.id.tv_center_adjust_line)
    TextView mTvCenterAdjustLine;
    @BindView(R.id.choose_date_left)
    WLXChooseLessonView mChooseDateLeft;
    @BindView(R.id.choose_date_right)
    WLXChooseLessonView mChooseDateRight;
    @BindView(R.id.reaicon)
    ImageView mReaicon;
    @BindView(R.id.flowRadioGroup)
    WLXFlowRadioGroup mFlowRadioGroup;


    private RadioButton[] radioButtons;
    private String[] titles = {"学习考试", "身体不适", "家中急事", "假日休息", "婚假产假"};
    private String[] reason_codes = {"study", "health", "housework", "holiday", "marriage"};
    private String reasonCode;
    private String start_date;//开始时间
    private String end_date;//结束时间
    private ArrayList<String> times = new ArrayList<>();

    public boolean isStopGrade = true;//是否是整个班级都停课
    private String mStudentId;
    private boolean hasChooseStudent = false;//是否选择了学生

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clazz_suspend);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        initTimes();
        initRadioButton();
        initView();
    }

    private void initTimes() {
        Calendar calendar = Calendar.getInstance();
        for (int i = 0; i < 30; i++) {
            int monthNum = calendar.get(Calendar.MONTH) + 1;
            int dayNum = calendar.get(Calendar.DAY_OF_MONTH);
            int year = calendar.get(Calendar.YEAR);
            String month = monthNum + "";
            String day = dayNum + "";
            if (monthNum < 10) {
                month = "0" + monthNum;
            }
            if (dayNum < 10) {
                day = "0" + dayNum;
            }

            String time = year + "年" + month + "月" + day + "日";
            times.add(time);

            //当前天数加1
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }
    }

    @OnClick({R.id.tv_save, R.id.choose_date_left, R.id.choose_date_right, R.id
            .rl_student_name_clazz_suspend, R.id
            .iv_back_clazz_suspend})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_save:
                if (checkIfComplete()) {
                    requestNet2Leave();
                }
                break;
            case R.id.iv_back_clazz_suspend:
                finish();
                break;
            case R.id.rl_student_name_clazz_suspend:
                Intent intent = new Intent(WLXClazzSuspendActivity.this,
                        WLXChooseStudentActivity.class);
                startActivityForResult(intent, 0);
                break;
            case R.id.choose_date_left:
                if (!hasChooseStudent) {
                    WLXCustomToast.show("请选择停课人员");
                    return ;
                }
                WLXWheelViewUtils.showOneWheel(this, times, "选择停课开始日期", 0, new OptionsPickerView
                        .OnOptionsSelectListener() {

                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3) {
                        String time = times.get(options1);
                        String[] split = time.split("年");
                        setChooseLesson(split[1], "开始", "", WLXChooseLessonView.ChooseMode
                                .YELLOWROUND);

                        start_date = time.replace("年", "-").replace("月", "-").replace("日", "-");
                    }
                });
                break;
            case R.id.choose_date_right:
                if (!hasChooseStudent) {
                    WLXCustomToast.show("请选择停课人员");
                    return ;
                }

                WLXWheelViewUtils.showOneWheel(this, times, "选择停课结束日期", 0, new OptionsPickerView
                        .OnOptionsSelectListener() {

                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3) {
                        String time = times.get(options1);
                        String[] split = time.split("年");
                        end_date = time.replace("年", "-").replace("月", "-").replace("日", "-");

                        int stopTimes = getStopTimes(start_date, end_date);
                        if (stopTimes == 0) {
                            WLXCustomToast.show("该段时间没有课,请重选!");
                            return;
                        }
                        setChooseLessonTo(split[1], "结束", "停课" + stopTimes + "次",
                                WLXChooseLessonView
                                        .ChooseMode.YELLOWROUND);
                    }
                });
                break;


        }
    }

    /**
     * 获取到停课的次数
     *
     * @param start_date 开始时间
     * @param end_date   结束时间
     */
    private int getStopTimes(String start_date, String end_date) {
        if (TextUtils.isEmpty(start_date) || TextUtils.isEmpty(end_date)) {
            WLXCustomToast.show("请选择开始或结束时间");
            return 0;
        }
        String format = "yyyy-MM-dd";
        long startDate = WLXDateUtil.getStringToDate(start_date, format);
        long endDate = WLXDateUtil.getStringToDate(end_date, format);
        if (startDate > endDate) {
            WLXCustomToast.show("您选择的开始时间大于结束时间");
            return 0;
        }
        List<wlx_schedule> list = WLXGreenDaoUtil.getScheduleDao().queryBuilder().where
                (wlx_scheduleDao.Properties.Grade_id
                                .eq(WLXConstant.GRADE_ID), wlx_scheduleDao.Properties
                                .Schedule_date.gt
                                        (startDate)
                        , wlx_scheduleDao.Properties.Schedule_date.le(endDate)).list();
        return list.size();
    }

    private void requestNet2Leave() {
        if (isStopGrade) {
            WLXHttpRxHelper.getInstance().scheduleStopGrade(WLXConstant.GRADE_ID, reasonCode,
                    start_date, end_date, new Subscriber<WLXGetCodeBean>() {


                        @Override
                        public void onCompleted() {
                        }

                        @Override
                        public void onError(Throwable e) {
                            WLXCustomToast.show("网络错误");
                        }

                        @Override
                        public void onNext(WLXGetCodeBean wlxGetCodeBean) {
                            if (wlxGetCodeBean.getCode() == 0) {
                                new AlertView("提示", "停课成功", null, new String[]{"确定"}, null,
                                        WLXClazzSuspendActivity.this,
                                        AlertView.Style.Alert, new OnItemClickListener() {
                                    @Override
                                    public void onItemClick(Object o, int position) {
                                        restoreState();
                                    }
                                }).show();
                            } else {
                                WLXCustomToast.show(wlxGetCodeBean.getMsg());
                            }
                        }
                    });
        } else {
            if (TextUtils.isEmpty(mStudentId)) {
                WLXCustomToast.show("未选择停课学生");
                return;
            }
            WLXHttpRxHelper.getInstance().scheduleStopStudent(WLXConstant.GRADE_ID, mStudentId,
                    reasonCode, start_date, end_date, new Subscriber<WLXGetCodeBean>() {

                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {
                            e.printStackTrace();
                        }

                        @Override
                        public void onNext(WLXGetCodeBean wlxGetCodeBean) {
                            if (wlxGetCodeBean.getCode() == 0) {
                                new AlertView("提示", "停课成功", null, new String[]{"确定"}, null,
                                        WLXClazzSuspendActivity.this,
                                        AlertView.Style.Alert, new OnItemClickListener() {
                                    @Override
                                    public void onItemClick(Object o, int position) {
                                        restoreState();
                                    }
                                }).show();
                            } else {
                                WLXCustomToast.show(wlxGetCodeBean.getMsg());
                            }
                        }
                    });
        }
    }


    //恢复到初始状态
    private void restoreState() {
        //恢复调课时间
        setChooseLesson("选择", "开始时间", "", WLXChooseLessonView.ChooseMode.GRAY);
        setChooseLessonTo("选择", "结束时间", "", WLXChooseLessonView.ChooseMode.GRAY);

        //停课人员
        mTvStudentNameClazzSuspend.setVisibility(View.GONE);
        hasChooseStudent = false;

    }

    //检查是否全部都选择了,并且请求数据已经OK
    private boolean checkIfComplete() {
        if (!hasChooseStudent) {
            WLXCustomToast.show("请选择停课人员");
            return false;
        }

        if (TextUtils.isEmpty(start_date)) {
            WLXCustomToast.show("请选择开始时间");
            return false;
        }
        if (TextUtils.isEmpty(end_date)) {
            WLXCustomToast.show("请选择结束时间");
            return false;
        }
        if (TextUtils.isEmpty(reasonCode)) {
            WLXCustomToast.show("请选择停课原因");
            return false;
        }

        return true;
    }


    private void initView() {
        mTvClazzSuspend.setText(WLXConstant.GRADE_TITLE);
        mFlowRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                for (int i = 0; i < radioButtons.length; i++) {
                    if (radioButtons[i].getId() == checkedId) {
                        //得到选中的文字对应编码
                        reasonCode = reason_codes[i];
                    }
                }
            }
        });
        setChooseLesson("选择", "调整课次", "", WLXChooseLessonView.ChooseMode.GRAY);
        setChooseLessonTo("选择", "调后课次", "", WLXChooseLessonView.ChooseMode.GRAY);
    }

    //上面+下面+模式:左边
    public void setChooseLesson(String top, String bottom, String line, WLXChooseLessonView
            .ChooseMode mode) {
        mChooseDateLeft.setTop(top);
        mChooseDateLeft.setBottom(bottom);
        mChooseDateLeft.changeMode(mode);
        mTvCenterAdjustLine.setText(line);
    }

    //上面+下面+模式:右边
    public void setChooseLessonTo(String top, String bottom, String line, WLXChooseLessonView
            .ChooseMode mode) {
        mChooseDateRight.setTop(top);
        mChooseDateRight.setBottom(bottom);
        mChooseDateRight.changeMode(mode);
        mTvCenterAdjustLine.setText(line);
    }


    /**
     * 动态添加内容
     */
    private void initRadioButton() {
        WindowManager manager = (WindowManager) this.getSystemService(WINDOW_SERVICE);
        int width = manager.getDefaultDisplay().getWidth();
        // 动态加载radiobutton的时候要用  radioGroup.layoutParams 来实现
        RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(width / 3 - 65,
                WRAP_CONTENT);
        layoutParams.setMargins(18, 13, 18, 10);
        radioButtons = new RadioButton[titles.length];
        for (int i = 0; i < radioButtons.length; i++) {
            radioButtons[i] = new RadioButton(this);
            radioButtons[i].setText(titles[i]);
            radioButtons[i].setButtonDrawable(null);
            radioButtons[i].setBackgroundResource(R.drawable.selector_feedback);
            radioButtons[i].setTextColor(this.getResources().getColorStateList(R.color
                    .color_feedback_name));
            radioButtons[i].setGravity(Gravity.CENTER);
            radioButtons[i].setTag(i);
            radioButtons[i].setId(i);
            radioButtons[i].setLayoutParams(layoutParams);
            mFlowRadioGroup.addView(radioButtons[i]);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_CANCELED) {
            hasChooseStudent = false;
            return;
        }
        if (resultCode == RESULT_OK) {
            hasChooseStudent = true;

            int student_id = data.getIntExtra(WLXChooseStudentActivity.STUDENT_ID, -1);
            String names = data.getStringExtra(WLXChooseStudentActivity.STUDENT_NAME);
            mTvStudentNameClazzSuspend.setVisibility(View.VISIBLE);
            mTvStudentNameClazzSuspend.setText(names + "");
            if (student_id == -1) {
                //选择了所有学生
                isStopGrade = true;
            } else {
                isStopGrade = false;
                mStudentId = student_id + "";
            }
        }
    }
}
